import Vue from "vue";
import Router from "vue-router";
import store from "@/store";
import http from "../utils/httpRequest";
import { isURL } from "@/utils/validate";
import { clearLoginInfo } from "@/utils";
import jwt_decode from "jwt-decode";
Vue.use(Router);

const _import = ll => () => import("@/views/" + ll);

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  {
    path: "/404",
    component: _import("common/404"),
    name: "404",
    meta: { title: "404未找到" }
  },
  {
    path: "/login",
    component: _import("common/login"),
    name: "login",
    meta: { title: "登录" }
  },
  {
    path: "/auth",
    component: _import("common/auth"),
    name: "auth",
    meta: { title: "权限不足" }
  }
];

const mainRoutes = {
  path: "/",
  component: _import("main"),
  name: "main",
  redirect: { name: "home" },
  meta: { title: "首页" },
  children: [
    {
      path: "/home",
      component: _import("home"),
      name: "home",
      meta: { title: "首页" }
    },
    {
      path: "/theme",
      component: _import("common/theme"),
      name: "theme",
      meta: { title: "主题" }
    },

    // {
    //   path: "/njry",
    //   component: _import("agricultural/njrydata"),
    //   name: "njry",
    //   meta: { title: "农技人员" }
    // },
    // {
    //   path: "/njsb",
    //   component: _import("agricultural/njsbdata"),
    //   name: "njsb",
    //   meta: { title: "农机设备" }
    // },
    // {
    //   path: "/znws",
    //   component: _import("agricultural/znwsdata"),
    //   name: "znws",
    //   meta: { title: "智能温室" }
    // },
    // {
    //   path: "/yjcp",
    //   component: _import("agricultural/yjcpdata"),
    //   name: "yjcp",
    //   meta: { title: "有机产品" }
    // },
    // {
    //   path: "/cpjc",
    //   component: _import("agricultural/cpjcdata"),
    //   name: "cpjc",
    //   meta: { title: "产品检测" }
    // },
    // {
    //   path: "/pyjd",
    //   component: _import("agricultural/pyjddata"),
    //   name: "pyjd",
    //   meta: { title: "培育基地" }
    // }
  ],
  beforeEnter: (to, from, next) => {
    console.log("beforeEnter");
    let token = JSON.parse(localStorage.getItem("token"));
    if (!token || !/\S/.test(token)) {
      clearLoginInfo();
      next({ name: "login" });
    }
    const decoded = jwt_decode(localStorage.getItem("token"));
    store.dispatch("setUser", decoded);
    next();
  }
};

const router = new Router({
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由,
  routes: globalRoutes.concat(mainRoutes)
});

router.beforeEach((to, from, next) => {
  console.log("beforeEach");
  if (
    router.options.isAddDynamicMenuRoutes ||
    to.name == "login" ||
    to.name == "auth" ||
    to.name == "404"
  ) {
    next();
  } else {
    // if(store.state.menuList!=[]){
    //   console.log("1")
    //   next()
    // }else{
    http({
      url: http.adornUrl("/sys/childmenu/nav"),
      method: "get",
      params: http.adornParams({
        name: "诸城2.0"
      })
    })
      .then(({ data }) => {
        if (data && data.code === 0) {
          // fnAddDynamicMenuRoutes(data.menuList)
          fnAddDynamicMenuRoutes(data.menuList);
          router.options.isAddDynamicMenuRoutes = true;
          store.dispatch("setMenu", data.menuList);

          next({ ...to, replace: true });
        } else {
          next();
        }
      })
      .catch(e => {
        console.log(
          `%c${e} 请求菜单列表和权限失败，跳转至登录页！！`,
          "color:blue"
        );
        router.push({ name: "login" });
      });
    // }
  }
});

function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  var temp = [];
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list);
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, "");
      var route = {
        path: "/" + menuList[i].url.replace("/", "-"),
        component: null,
        name: menuList[i].url.replace("/", "-"),
        meta: {
          menuId: menuList[i].id,
          title: menuList[i].name,
          requireAuth: menuList[i].require_auth == 1 ? true : false,
          isDynamic: true,
          isTab: true,
          iframeUrl: ""
        }
      };
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route["path"] = `i-${menuList[i].id}`;
        route["name"] = `i-${menuList[i].id}`;
        route["meta"]["iframeUrl"] = menuList[i].url;
      } else {
        try {
          route["component"] = _import(`${menuList[i].url}`) || null;
        } catch (e) {}
      }
      routes.push(route);
      console.log(route);
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes);
  } else {
    mainRoutes.name = "main-dynamic";
    mainRoutes.children = routes;
    router.addRoutes([mainRoutes, { path: "*", redirect: { name: "404" } }]);
    store.dispatch(
      "setDynamicRoute",
      JSON.stringify(mainRoutes.children || "[]")
    );
    console.log(mainRoutes);
  }
}
export default router;
